/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-11-08     balanceTWK   first version
 */

#include <board.h>
#include "drv_gpio.h"
#include "drv_soft_i2c.h"

#ifdef RT_USING_I2C

//#define DRV_DEBUG
#define LOG_TAG              "drv.i2c"
#include <drv_log.h>
//#define LOG_D rt_kprintf
//#define LOG_W rt_kprintf
#if !defined(BSP_USING_SOFT_I2C0) && !defined(BSP_USING_SOFT_I2C1) && !defined(BSP_USING_SOFT_I2C2) && !defined(BSP_USING_SOFT_I2C3) && !defined(BSP_USING_SOFT_I2C4)
#error "Please define at least one BSP_USING_SOFT_I2Cx"
/* this driver can be disabled at menuconfig → RT-Thread Components → Device Drivers */
#endif

static struct soft_i2c_config soft_i2c_config[] =
{
#ifdef BSP_USING_SOFT_I2C0
    I2C0_BUS_CONFIG,
#endif
#ifdef BSP_USING_SOFT_I2C1
    I2C1_BUS_CONFIG,
#endif
#ifdef BSP_USING_SOFT_I2C2
    I2C2_BUS_CONFIG,
#endif
#ifdef BSP_USING_SOFT_I2C3
    I2C3_BUS_CONFIG,
#endif
#ifdef BSP_USING_SOFT_I2C4
    I2C4_BUS_CONFIG,
#endif
};

static struct rt_soft_i2c_bus i2c_obj[sizeof(soft_i2c_config) / sizeof(soft_i2c_config[0])];

/**
 * This function initializes the i2c pin.
 *
 * @param Stm32 i2c dirver class.
 */
static void soft_i2c_gpio_init(const struct soft_i2c_config *cfg)
{
    nu_gpio_mode(cfg->scl, PIN_MODE_OUTPUT_OD);
    nu_gpio_mode(cfg->sda, PIN_MODE_OUTPUT_OD);

    nu_gpio_write(cfg->scl, PIN_HIGH);
    nu_gpio_write(cfg->sda, PIN_HIGH);
}

/**
 * if i2c is locked, this function will unlock it
 *
 * @param stm32 config class
 *
 * @return RT_EOK indicates successful unlock.
 */
static rt_err_t soft_i2c_bus_unlock(const struct soft_i2c_config *cfg)
{
    rt_int32_t i = 0;

    if (PIN_LOW == nu_gpio_read(cfg->sda))
    {
        while (i++ < 9)
        {
            nu_gpio_write(cfg->scl, PIN_HIGH);
            rt_hw_us_delay(100);
            nu_gpio_write(cfg->scl, PIN_LOW);
            rt_hw_us_delay(100);
        }
    }
    if (PIN_LOW == nu_gpio_read(cfg->sda))
    {
        return -RT_ERROR;
    }

    return RT_EOK;
}

rt_inline void i2c_delay(const struct soft_i2c_config *cfg)
{
    rt_hw_us_delay((cfg->delay_us + 1) >> 1);
}

rt_inline void i2c_delay2(const struct soft_i2c_config *cfg)
{
    rt_hw_us_delay(cfg->delay_us);
}

/**
 * release scl line, and wait scl line to high.
 */
static rt_err_t SCL_H(const struct soft_i2c_config *cfg)
{
    rt_tick_t start;

    SET_SCL(cfg->scl, 1);

    start = rt_tick_get();
    SCL_MODE_IN(cfg->scl);
    while (!GET_SCL(cfg->scl))
    {
        if ((rt_tick_get() - start) > cfg->timeout) {
            SCL_MODE_OUT(cfg->scl);
            return -RT_ETIMEOUT;
        }
        rt_thread_delay(1);
    }
    SCL_MODE_OUT(cfg->scl);
#ifdef RT_I2C_BITOPS_DEBUG
    if (rt_tick_get() != start)
    {
        LOG_D("wait %ld tick for SCL line to go high",
              rt_tick_get() - start);
    }
#endif

    i2c_delay(cfg);

    return RT_EOK;
}

static void i2c_start(const struct soft_i2c_config *cfg)
{
#ifdef RT_I2C_BITOPS_DEBUG
    if (!GET_SCL(cfg->scl))
    {
        LOG_E("I2C bus error, SCL line low");
    }
    if (!GET_SDA(cfg->sda))
    {
        LOG_E("I2C bus error, SDA line low");
    }
#endif
    SDA_L(cfg);
    i2c_delay(cfg);
    SCL_L(cfg);
}

static void i2c_restart(const struct soft_i2c_config *cfg)
{
    SDA_H(cfg);
    SCL_H(cfg);
    i2c_delay(cfg);
    SDA_L(cfg);
    i2c_delay(cfg);
    SCL_L(cfg);
}

static void i2c_stop(const struct soft_i2c_config *cfg)
{
    SDA_L(cfg);
    i2c_delay(cfg);
    SCL_H(cfg);
    i2c_delay(cfg);
    SDA_H(cfg);
    i2c_delay2(cfg);
}

/*rt_inline*/ rt_bool_t i2c_waitack(const struct soft_i2c_config *cfg)
{
    rt_bool_t ack;

//    SDA_H(cfg);
    i2c_delay(cfg);

    if (SCL_H(cfg) < 0)
    {
        LOG_W("wait ack timeout\n");

        return -RT_ETIMEOUT;
    }
    i2c_delay(cfg);

    ack = !GET_SDA(cfg->sda);    /* ACK : SDA pin is pulled low */
    LOG_D("%s\n", ack ? "ACK" : "NACK");

    SCL_L(cfg);
    SDA_MODE_OUT(cfg->sda);

    return ack;
}

static rt_int32_t i2c_writeb(struct rt_i2c_bus_device *bus, rt_uint8_t data)
{
    rt_int32_t i;
    rt_uint8_t bit;

    const struct soft_i2c_config *cfg = (struct soft_i2c_config *)bus->priv;

    for (i = 7; i >= 0; i--)
    {
        SCL_L(cfg);
        bit = (data >> i) & 1;
        SET_SDA(cfg->sda, bit);
        i2c_delay(cfg);
        if (SCL_H(cfg) < 0)
        {
            LOG_D("i2c_writeb: 0x%02x, "
                    "wait scl pin high timeout at bit %d\n",
                    data, i);

            return -RT_ETIMEOUT;
        }
    }
    SCL_L(cfg);
    i2c_delay2(cfg);
    SDA_MODE_IN(cfg->sda);

    return i2c_waitack(cfg);
}

static rt_int32_t i2c_readb(struct rt_i2c_bus_device *bus)
{
    rt_uint8_t i;
    rt_uint8_t data = 0;
    const struct soft_i2c_config *cfg = (struct soft_i2c_config *)bus->priv;

    SDA_H(cfg);
    SDA_MODE_IN(cfg->sda);
    i2c_delay(cfg);
    for (i = 0; i < 8; i++)
    {
        data <<= 1;

        if (SCL_H(cfg) < 0)
        {
            LOG_D("i2c_readb: wait scl pin high "
                    "timeout at bit %d\n", 7 - i);

            return -RT_ETIMEOUT;
        }

        if (GET_SDA(cfg->sda))
            data |= 1;
        SCL_L(cfg);
        i2c_delay2(cfg);
    }
    SDA_MODE_OUT(cfg->sda);

    return data;
}

static rt_size_t i2c_send_bytes(struct rt_i2c_bus_device *bus,
                                struct rt_i2c_msg        *msg)
{
    rt_int32_t ret;
    rt_size_t bytes = 0;
    const rt_uint8_t *ptr = msg->buf;
    rt_int32_t count = msg->len;
    rt_uint16_t ignore_nack = msg->flags & RT_I2C_IGNORE_NACK;
    register rt_base_t level;

    while (count > 0)
    {
        level = rt_hw_interrupt_disable();
        ret = i2c_writeb(bus, *ptr);
        rt_hw_interrupt_enable(level);

        if ((ret > 0) || (ignore_nack && (ret == 0)))
        {
            count --;
            ptr ++;
            bytes ++;
        }
        else if (ret == 0)
        {
            LOG_D("send bytes: NACK.\n");

            return 0;
        }
        else
        {
            LOG_E("send bytes: error %d", ret);

            return ret;
        }
    }

    return bytes;
}

static rt_err_t i2c_send_ack_or_nack(struct rt_i2c_bus_device *bus, int ack)
{
    const struct soft_i2c_config *cfg = (struct soft_i2c_config *)bus->priv;

    if (ack)
        SET_SDA(cfg->sda, 0);
    i2c_delay(cfg);
    if (SCL_H(cfg) < 0)
    {
        LOG_E("ACK or NACK timeout.");

        return -RT_ETIMEOUT;
    }
    SCL_L(cfg);

    return RT_EOK;
}

static rt_size_t i2c_recv_bytes(struct rt_i2c_bus_device *bus,
                                struct rt_i2c_msg        *msg)
{
    rt_int32_t val;
    rt_int32_t bytes = 0;   /* actual bytes */
    rt_uint8_t *ptr = msg->buf;
    rt_int32_t count = msg->len;
    const rt_uint32_t flags = msg->flags;

    while (count > 0)
    {
        val = i2c_readb(bus);
        if (val >= 0)
        {
            *ptr = val;
            bytes ++;
        }
        else
        {
            break;
        }

        ptr ++;
        count --;

        LOG_D("recieve bytes: 0x%02x, %s\n",
                val, (flags & RT_I2C_NO_READ_ACK) ?
                "(No ACK/NACK)" : (count ? "ACK" : "NACK"));

        if (!(flags & RT_I2C_NO_READ_ACK))
        {
            val = i2c_send_ack_or_nack(bus, count);
            if (val < 0)
                return val;
        }
    }

    return bytes;
}

static rt_int32_t i2c_send_address(struct rt_i2c_bus_device *bus,
                                   rt_uint8_t                addr,
                                   rt_int32_t                retries)
{
    const struct soft_i2c_config *cfg = (struct soft_i2c_config *)bus->priv;
    rt_int32_t i;
    rt_err_t ret = 0;
    register rt_base_t level;

    for (i = 0; i <= retries; i++)
    {
        level = rt_hw_interrupt_disable();
        ret = i2c_writeb(bus, addr);
        rt_hw_interrupt_enable(level);
        if (ret == 1 || i == retries)
            break;
        LOG_D("send stop condition\n");
        i2c_stop(cfg);
        i2c_delay2(cfg);
        LOG_D("send start condition\n");
        i2c_start(cfg);
    }

    return ret;
}

static rt_err_t i2c_bit_send_address(struct rt_i2c_bus_device *bus,
                                     struct rt_i2c_msg        *msg)
{
    rt_uint16_t flags = msg->flags;
    rt_uint16_t ignore_nack = msg->flags & RT_I2C_IGNORE_NACK;
    struct soft_i2c_config *cfg = (struct soft_i2c_config *)bus->priv;

    rt_uint8_t addr1, addr2;
    rt_int32_t retries;
    rt_err_t ret;
    register rt_base_t level;

    retries = ignore_nack ? 0 : bus->retries;

    if (flags & RT_I2C_ADDR_10BIT)
    {
        addr1 = 0xF0 | ((msg->addr >> 7) & 0x06);
        addr2 = msg->addr & 0xFF;

        LOG_D("addr1: %d, addr2: %d\n", addr1, addr2);

        ret = i2c_send_address(bus, addr1, retries);
        if ((ret != 1) && !ignore_nack)
        {
            LOG_W("NACK: sending first addr\n");

            return -RT_EIO;
        }

        level = rt_hw_interrupt_disable();
        ret = i2c_writeb(bus, addr2);
        rt_hw_interrupt_enable(level);
        if ((ret != 1) && !ignore_nack)
        {
            LOG_W("NACK: sending second addr\n");

            return -RT_EIO;
        }
        if (flags & RT_I2C_RD)
        {
            LOG_D("send repeated start condition\n");
            i2c_restart(cfg);
            addr1 |= 0x01;
            ret = i2c_send_address(bus, addr1, retries);
            if ((ret != 1) && !ignore_nack)
            {
                LOG_E("NACK: sending repeated addr");

                return -RT_EIO;
            }
        }
    }
    else
    {
        /* 7-bit addr */
        addr1 = msg->addr << 1;
        if (flags & RT_I2C_RD)
            addr1 |= 1;
        ret = i2c_send_address(bus, addr1, retries);
        if ((ret != 1) && !ignore_nack)
            return -RT_EIO;
    }

    return RT_EOK;
}

static rt_size_t i2c_master_xfer(struct rt_i2c_bus_device *bus,
                                 struct rt_i2c_msg         msgs[],
                                 rt_uint32_t               num)
{
    struct rt_i2c_msg *msg;
    struct soft_i2c_config *cfg = (struct soft_i2c_config *)bus->priv;
    rt_int32_t i, ret;
    rt_uint16_t ignore_nack;

    if (num == 0) return 0;

    for (i = 0; i < num; i++)
    {
        msg = &msgs[i];
        ignore_nack = msg->flags & RT_I2C_IGNORE_NACK;
        if (!(msg->flags & RT_I2C_NO_START))
        {
            if (i)
            {
                i2c_restart(cfg);
            }
            else
            {
                LOG_D("send start condition\n");
                i2c_start(cfg);
            }
            ret = i2c_bit_send_address(bus, msg);
            if ((ret != RT_EOK) && !ignore_nack)
            {
                LOG_D("receive NACK from device addr 0x%02x msg %d\n",
                        msgs[i].addr, i);
                goto out;
            }
        }
        if (msg->flags & RT_I2C_RD)
        {
            ret = i2c_recv_bytes(bus, msg);
            if (ret >= 1)
                LOG_D("read %d byte%s\n", ret, ret == 1 ? "" : "s");
            if (ret < msg->len)
            {
                if (ret >= 0)
                    ret = -RT_EIO;
                goto out;
            }
        }
        else
        {
            ret = i2c_send_bytes(bus, msg);
            if (ret >= 1)
                LOG_D("write %d byte%s\n", ret, ret == 1 ? "" : "s");
            if (ret < msg->len)
            {
                if (ret >= 0)
                    ret = -RT_ERROR;
                goto out;
            }
        }
    }
    ret = i;

out:
    if (!(msg->flags & RT_I2C_NO_STOP))
    {
        LOG_D("send stop condition\n");
        i2c_stop(cfg);
    }

    return ret;
}

static const struct rt_i2c_bus_device_ops stm32_bus_ops = {
    .master_xfer = i2c_master_xfer,
    .i2c_bus_control = RT_NULL
};

/* I2C initialization function */
int rt_soft_i2c_init(void)
{
    rt_size_t obj_num = sizeof(i2c_obj) / sizeof(struct rt_soft_i2c_bus);
    rt_err_t result;
    int i;

    for (i = 0; i < obj_num; i++)
    {
        i2c_obj[i].i2c_bus.ops = &stm32_bus_ops;
        i2c_obj[i].i2c_bus.priv = &soft_i2c_config[i];

        soft_i2c_gpio_init(&soft_i2c_config[i]);

        soft_i2c_bus_unlock(&soft_i2c_config[i]);

        result = rt_i2c_bus_device_register(&i2c_obj[i].i2c_bus, soft_i2c_config[i].bus_name);
        RT_ASSERT(result == RT_EOK);

        LOG_D("software simulation %s init done, pin scl: %d, pin sda %d\n",
                soft_i2c_config[i].bus_name,
                soft_i2c_config[i].scl,
                soft_i2c_config[i].sda);
    }

    return RT_EOK;
}
INIT_BOARD_EXPORT(rt_soft_i2c_init);

#endif /* RT_USING_I2C */
